package com.sais.manage.boot.platform.service.impl;


import com.sais.common.utils.RsaUtils;
import com.sais.common.utils.UUIDUtils;
import com.sais.manage.boot.platform.dto.UserLoginDTO;
import com.sais.manage.boot.platform.entity.Rsa;
import com.sais.manage.boot.platform.mapper.RsaMapper;
import com.sais.manage.boot.platform.mapper.UserMapper;
import com.sais.manage.boot.platform.service.IRsaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 基础平台-信息加密 service 实现类
 *
 * @author zwp
 * @date 2020/3/14
 **/
@Slf4j
@Service
public class RsaServiceImpl implements IRsaService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RsaMapper rsaMapper;

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public String getPublicKey(String account) throws Exception {
        UserLoginDTO loginDTO = userMapper.selectUserByAccount(account);
        if (loginDTO == null){
            throw new RuntimeException("账号不存在！");
        }
        String userId = loginDTO.getUkId();

        //根据账号 先从 rsa 中查询 看该用户使用已经有公钥私钥 有返回，没有创建
        Rsa userRsa = rsaMapper.selectById(userId);
        if (userRsa != null){
           return userRsa.getPublicKey();
        }else {
            RsaUtils.genKeyPair();
            String publicKey = RsaUtils.keyMap.get(0);
            String privateKey = RsaUtils.keyMap.get(1);

            Rsa rsa = Rsa.builder()
                    .ukId(UUIDUtils.getLower())
                    .userId(userId)
                    .publicKey(publicKey)
                    .privateKey(privateKey)
                    .build();

            rsaMapper.insert(rsa);
            return publicKey;
        }
    }

}
